import os
import random
import shutil
import time
import xml.etree.ElementTree as ET
from shutil import copyfile
from xml.dom.minidom import Document
from ultralytics import YOLO

import cv2

videoDir = r"D:\ChromeCoreDownloads\py\video"
root = r"E:\ideaworkspace3\ultralytics"
biaozhuRoot = os.path.join(root, "VOCdevkit\\biaozhu\\")
vocRoot = os.path.join(root, "VOCdevkit\\VOC2007\\")

classes = {
    "0": "character",
    "1": "money",
    "2": "item",
    "3": "epic",
    "4": "open_door",
    "5": "close_door",
    "6": "guai_wu",
    "7": "shang_ren",
    "8": "fan_pai",
    "9": "purple_card",
    "10": "change_role",
    "11": "abyss",
}

TRAIN_RATIO = 90


def mp4ToPic():
    biaozhuImgDir = os.path.join(biaozhuRoot, "JPEGImages/")

    clearVocDir(biaozhuImgDir)

    files = os.listdir(videoDir)
    for file in files:
        file_path = os.path.join(videoDir, file)
        if os.path.isfile(file_path) and file.endswith(".mp4"):
            cap = cv2.VideoCapture(file_path)

            frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            frame_rate = int(cap.get(cv2.CAP_PROP_FPS))

            target_interval = 10
            if frame_rate < target_interval:
                target_interval = frame_rate

            c = 1
            cut_num = 0
            while c <= frame_count:
                ok, frame = cap.read()
                if not ok:
                    break
                if c % target_interval == 0 or c == frame_count:
                    writePath = biaozhuImgDir + str(int(time.time() * 1000000)) + ".jpg"
                    cv2.imwrite(writePath, frame)
                    cut_num += 1

                c += 1

            cap.release()
            cv2.destroyAllWindows()
            print("mp4 task -> total: %d, cut: %d" % (frame_count, cut_num))


def predictBiaoZhu():
    wd = os.getcwd()
    model = YOLO(os.path.join(wd, "model.yaml"))
    model = YOLO(os.path.join(wd, "best.pt"))

    pic_Path = os.path.join(biaozhuRoot, "JPEGImages/")
    txt_path = os.path.join(biaozhuRoot, "Annotations/")
    model(source=pic_Path, save=False, save_txt=True, imgsz=1280, name=os.path.join(biaozhuRoot, "Annotations/tmpxml/"))

    yoloTxtPath = ""
    fileList = os.listdir(txt_path)
    if len(fileList) == 1:
        yoloTxtPath = os.path.join(txt_path, fileList[0] + "\\labels\\")

    counts = list()
    for xf in fileList:
        num = xf.replace("tmpxml", "")
        if num == '':
            counts.append(1)
        else:
            counts.append(int(num))

    counts.sort(reverse=True)
    if counts[0] == 1:
        yoloTxtPath = os.path.join(txt_path, "tmpxml\\labels\\")
    else:
        yoloTxtPath = os.path.join(txt_path, "tmpxml" + str(counts[0]) + "\\labels\\")

    txtToXml(pic_Path, yoloTxtPath, txt_path)

    try:
        shutil.rmtree(yoloTxtPath)
    except Exception as e:
        print(f"Error while deleting folder: {e}")
    print("end !")


def biaozhuTovoc2007():
    clearVocDir(vocRoot + "Annotations")
    clearVocDir(vocRoot + "JPEGImages")
    clearVocDir(vocRoot + "YOLOLabels")
    # clearVocDir(root+"VOCdevkit/images")
    # clearVocDir(root+"VOCdevkit/labels")

    arr = list()

    files = os.listdir(biaozhuRoot + "Annotations")
    for file in files:
        xml = os.path.join(biaozhuRoot + "Annotations/", file)
        xmlw = os.path.join(vocRoot + "Annotations/", file)

        if os.path.isdir(xml):
            continue

        for suffix in [".jpg"]:
            jpg = os.path.join(biaozhuRoot + "JPEGImages/", file.replace(".xml", suffix))

            if os.path.exists(jpg):
                jpgw = os.path.join(vocRoot + "JPEGImages/", file.replace(".xml", suffix))
                shutil.copy(xml, xmlw)
                shutil.copy(jpg, jpgw)
                arr.append(xml)
                arr.append(jpg)
                break

    for p in arr:
        os.remove(p)

    vocToTxt()
    print("biaozhuTovoc2007 end!")


def clearVocDir(dir_path):
    if os.path.exists(dir_path):
        try:
            shutil.rmtree(dir_path)
            os.mkdir(dir_path)
        except Exception as e:
            print(f"Error while deleting folder: {e}")
    else:
        os.mkdir(dir_path)


def vocToTxt():
    wd = os.getcwd()
    data_base_dir = os.path.join(wd, "VOCdevkit/")
    if not os.path.isdir(data_base_dir):
        os.mkdir(data_base_dir)
    work_sapce_dir = os.path.join(data_base_dir, "VOC2007/")
    if not os.path.isdir(work_sapce_dir):
        os.mkdir(work_sapce_dir)
    annotation_dir = os.path.join(work_sapce_dir, "Annotations/")
    if not os.path.isdir(annotation_dir):
        os.mkdir(annotation_dir)
    clear_hidden_files(annotation_dir)
    image_dir = os.path.join(work_sapce_dir, "JPEGImages/")
    if not os.path.isdir(image_dir):
        os.mkdir(image_dir)
    clear_hidden_files(image_dir)
    yolo_labels_dir = os.path.join(work_sapce_dir, "YOLOLabels/")
    if not os.path.isdir(yolo_labels_dir):
        os.mkdir(yolo_labels_dir)
    clear_hidden_files(yolo_labels_dir)
    yolov5_images_dir = os.path.join(data_base_dir, "images/")
    if not os.path.isdir(yolov5_images_dir):
        os.mkdir(yolov5_images_dir)
    clear_hidden_files(yolov5_images_dir)
    yolov5_labels_dir = os.path.join(data_base_dir, "labels/")
    if not os.path.isdir(yolov5_labels_dir):
        os.mkdir(yolov5_labels_dir)
    clear_hidden_files(yolov5_labels_dir)
    yolov5_images_train_dir = os.path.join(yolov5_images_dir, "train/")
    if not os.path.isdir(yolov5_images_train_dir):
        os.mkdir(yolov5_images_train_dir)
    clear_hidden_files(yolov5_images_train_dir)
    yolov5_images_test_dir = os.path.join(yolov5_images_dir, "val/")
    if not os.path.isdir(yolov5_images_test_dir):
        os.mkdir(yolov5_images_test_dir)
    clear_hidden_files(yolov5_images_test_dir)
    yolov5_labels_train_dir = os.path.join(yolov5_labels_dir, "train/")
    if not os.path.isdir(yolov5_labels_train_dir):
        os.mkdir(yolov5_labels_train_dir)
    clear_hidden_files(yolov5_labels_train_dir)
    yolov5_labels_test_dir = os.path.join(yolov5_labels_dir, "val/")
    if not os.path.isdir(yolov5_labels_test_dir):
        os.mkdir(yolov5_labels_test_dir)
    clear_hidden_files(yolov5_labels_test_dir)

    train_file = open(os.path.join(wd, "yolov5_train.txt"), 'w')
    test_file = open(os.path.join(wd, "yolov5_val.txt"), 'w')
    train_file.close()
    test_file.close()
    train_file = open(os.path.join(wd, "yolov5_train.txt"), 'a')
    test_file = open(os.path.join(wd, "yolov5_val.txt"), 'a')
    list_imgs = os.listdir(image_dir)  # list image files
    prob = random.randint(1, 100)
    print("Probability: %d" % prob)
    for i in range(0, len(list_imgs)):
        path = os.path.join(image_dir, list_imgs[i])
        if os.path.isfile(path):
            image_path = image_dir + list_imgs[i]
            voc_path = list_imgs[i]
            (nameWithoutExtention, extention) = os.path.splitext(os.path.basename(image_path))
            (voc_nameWithoutExtention, voc_extention) = os.path.splitext(os.path.basename(voc_path))
            annotation_name = nameWithoutExtention + '.xml'
            annotation_path = os.path.join(annotation_dir, annotation_name)
            label_name = nameWithoutExtention + '.txt'
            label_path = os.path.join(yolo_labels_dir, label_name)
        prob = random.randint(1, 100)
        print("Probability: %d" % prob)
        if (prob < TRAIN_RATIO):  # train dataset
            if os.path.exists(annotation_path):
                train_file.write(image_path + '\n')
                convert_annotation(nameWithoutExtention)  # convert label
                copyfile(image_path, yolov5_images_train_dir + voc_path)
                copyfile(label_path, yolov5_labels_train_dir + label_name)
        else:
            if os.path.exists(annotation_path):
                test_file.write(image_path + '\n')
                convert_annotation(nameWithoutExtention)  # convert label
                copyfile(image_path, yolov5_images_test_dir + voc_path)
                copyfile(label_path, yolov5_labels_test_dir + label_name)
    train_file.close()
    test_file.close()


def txtToXml(picPath, txtPath, xmlPath):  # txt所在文件夹路径，xml文件保存路径，图片所在文件夹路径
    """此函数用于将yolo格式txt标注文件转换为voc格式xml标注文件
	在自己的标注图片文件夹下建三个子文件夹，分别命名为picture、txt、xml
	"""

    files = os.listdir(txtPath)
    for i, name in enumerate(files):
        xmlBuilder = Document()
        annotation = xmlBuilder.createElement("annotation")  # 创建annotation标签
        xmlBuilder.appendChild(annotation)
        txtFile = open(os.path.join(txtPath, name))
        txtList = txtFile.readlines()

        picFilePath = os.path.join(picPath, name[0:-4] + ".jpg")
        if not os.path.exists(picFilePath):
            continue

        img = cv2.imread(picFilePath)
        Pheight, Pwidth, Pdepth = img.shape

        folder = xmlBuilder.createElement("folder")  # folder标签
        foldercontent = xmlBuilder.createTextNode("driving_annotation_dataset")
        folder.appendChild(foldercontent)
        annotation.appendChild(folder)  # folder标签结束

        filename = xmlBuilder.createElement("filename")  # filename标签
        filenamecontent = xmlBuilder.createTextNode(name[0:-4] + ".jpg")
        filename.appendChild(filenamecontent)
        annotation.appendChild(filename)  # filename标签结束

        size = xmlBuilder.createElement("size")  # size标签
        width = xmlBuilder.createElement("width")  # size子标签width
        widthcontent = xmlBuilder.createTextNode(str(Pwidth))
        width.appendChild(widthcontent)
        size.appendChild(width)  # size子标签width结束

        height = xmlBuilder.createElement("height")  # size子标签height
        heightcontent = xmlBuilder.createTextNode(str(Pheight))
        height.appendChild(heightcontent)
        size.appendChild(height)  # size子标签height结束

        depth = xmlBuilder.createElement("depth")  # size子标签depth
        depthcontent = xmlBuilder.createTextNode(str(Pdepth))
        depth.appendChild(depthcontent)
        size.appendChild(depth)  # size子标签depth结束

        annotation.appendChild(size)  # size标签结束

        for j in txtList:
            oneline = j.strip().split(" ")
            object = xmlBuilder.createElement("object")  # object 标签
            picname = xmlBuilder.createElement("name")  # name标签
            namecontent = xmlBuilder.createTextNode(classes[oneline[0]])
            picname.appendChild(namecontent)
            object.appendChild(picname)  # name标签结束

            pose = xmlBuilder.createElement("pose")  # pose标签
            posecontent = xmlBuilder.createTextNode("Unspecified")
            pose.appendChild(posecontent)
            object.appendChild(pose)  # pose标签结束

            truncated = xmlBuilder.createElement("truncated")  # truncated标签
            truncatedContent = xmlBuilder.createTextNode("0")
            truncated.appendChild(truncatedContent)
            object.appendChild(truncated)  # truncated标签结束

            difficult = xmlBuilder.createElement("difficult")  # difficult标签
            difficultcontent = xmlBuilder.createTextNode("0")
            difficult.appendChild(difficultcontent)
            object.appendChild(difficult)  # difficult标签结束

            bndbox = xmlBuilder.createElement("bndbox")  # bndbox标签
            xmin = xmlBuilder.createElement("xmin")  # xmin标签
            mathData = int(((float(oneline[1])) * Pwidth + 1) - (float(oneline[3])) * 0.5 * Pwidth)
            xminContent = xmlBuilder.createTextNode(str(mathData))
            xmin.appendChild(xminContent)
            bndbox.appendChild(xmin)  # xmin标签结束

            ymin = xmlBuilder.createElement("ymin")  # ymin标签
            mathData = int(((float(oneline[2])) * Pheight + 1) - (float(oneline[4])) * 0.5 * Pheight)
            yminContent = xmlBuilder.createTextNode(str(mathData))
            ymin.appendChild(yminContent)
            bndbox.appendChild(ymin)  # ymin标签结束

            xmax = xmlBuilder.createElement("xmax")  # xmax标签
            mathData = int(((float(oneline[1])) * Pwidth + 1) + (float(oneline[3])) * 0.5 * Pwidth)
            xmaxContent = xmlBuilder.createTextNode(str(mathData))
            xmax.appendChild(xmaxContent)
            bndbox.appendChild(xmax)  # xmax标签结束

            ymax = xmlBuilder.createElement("ymax")  # ymax标签
            mathData = int(((float(oneline[2])) * Pheight + 1) + (float(oneline[4])) * 0.5 * Pheight)
            ymaxContent = xmlBuilder.createTextNode(str(mathData))
            ymax.appendChild(ymaxContent)
            bndbox.appendChild(ymax)  # ymax标签结束

            object.appendChild(bndbox)  # bndbox标签结束

            annotation.appendChild(object)  # object标签结束

        f = open(os.path.join(xmlPath, name[0:-4] + ".xml"), 'w')
        xmlBuilder.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8')
        f.close()


def clear_hidden_files(path):
    dir_list = os.listdir(path)
    for i in dir_list:
        abspath = os.path.join(os.path.abspath(path), i)
        if os.path.isfile(abspath):
            if i.startswith("._"):
                os.remove(abspath)
        else:
            clear_hidden_files(abspath)


def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(image_id):
    in_file = open('VOCdevkit/VOC2007/Annotations/%s.xml' % image_id)
    out_file = open('VOCdevkit/VOC2007/YOLOLabels/%s.txt' % image_id, 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    classVals = list(classes.values())
    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classVals or int(difficult) == 1:
            continue
        cls_id = classVals.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
             float(xmlbox.find('ymax').text))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
    in_file.close()
    out_file.close()


if __name__ == '__main__':
    mp4ToPic()
    # predictBiaoZhu()
    # biaozhuTovoc2007()

    # picPath = r"E:\ideaworkspace3\ultralytics\VOCdevkit\images\val"
    # txtPath = r"E:\ideaworkspace3\ultralytics\VOCdevkit\labels\val"
    # xmlPath = r"E:\ideaworkspace3\ultralytics\VOCdevkit\biaozhu\Annotations"
    # txtToXml(picPath, txtPath, xmlPath)
